<template>
  <div class="app-container">
    <el-upload class="upload-demo" drag :action="uploadUrl" :headers="headers" :on-success="handleSuccess" :show-file-list="false" :before-upload="beforeUpload" :multiple="false">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传指定格式的 excel 文件，且不超过20MB</div>
    </el-upload>
    <el-button type="primary" @click="parseExcelFile">解析</el-button>
  </div>

</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { getToken } from '@/utils/auth'
import { parseExcelV1, parseExcelV2 } from '@/api/admin-enterprise'
export default {
  name: 'EnterpriseImport',
  components: { UploadExcelComponent },
  data() {
    return {
      parseForm: {
        file_name: "",
        file_abs_path: "",
      },
      // 企业信息导入
      uploadUrl: process.env.VUE_APP_BASE_API + '/file/upload',
      headers: {
        Authorization: "Bearer " + getToken() // 从cookie里获取token，并赋值  Authorization ，而不是token
      },
    }
  },
  methods: {
    parseExcelFile() {
      parseExcelV1(this.parseForm).then((res) => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
      }).catch((e) => {
        this.$message({
          message: e,
          type: 'error'
        })
      })
    },
    beforeUpload(file) {
      if (!file) {
        this.$message({
          message: '请选择文件',
          type: 'error'
        })
        return false
      }
      const fileType = file.name.split('.').pop().toLowerCase();
      if (fileType !== 'xlsx' && fileType !== 'xls') {
        this.$message({
          message: '只允许上传Excel文件',
          type: 'error'
        })
        return false;
      }
      const isLt1M = file.size / 1024 / 1024 < 20
      if (isLt1M) {
        return true
      }
      this.$message({
        message: '请不要上传超过20MB的文件',
        type: 'warning'
      })
      return false
    },
    handleSuccess(data) {
      this.parseForm.file_name = data.data.file_name
      this.parseForm.file_abs_path = data.data.file_path
    }
  }
}

</script>

<style scoped>
</style>